package com.polly.esphwevent.common.disruptor;

import com.lmax.disruptor.RingBuffer;
import lombok.extern.slf4j.Slf4j;

/**
 * @title: HomeworkEventProducer
 * @description: TODO(用一句话描述该文件做什么)
 * @date: 2019/2/12 14:48
 * @author ldz112@163.com
 * @version V1.0
 */
@Slf4j
public class HomeworkEventProducer {

    private final RingBuffer<HomeworkEvent> ringBuffer;

    public HomeworkEventProducer(RingBuffer<HomeworkEvent> ringBuffer){
        this.ringBuffer = ringBuffer;
    }

    public void publishEvent(HomeworkEvent assessmentEvent){
        //1.可以把ringBuffer看做一个事件队列，那么next就是得到下面一个事件槽
        long sequence = ringBuffer.next();
        try {
            //2.用上面的索引取出一个空的事件用于填充（获取该序号对应的事件对象）
            HomeworkEvent event = ringBuffer.get(sequence);
            //3.获取要通过事件传递的业务数据
            event.setEventType(assessmentEvent.getEventType());
            event.setHomeworkId(assessmentEvent.getHomeworkId());
            event.setUserId(assessmentEvent.getUserId());
        } finally {
            //4.发布事件
            //注意，最后的 ringBuffer.publish 方法必须包含在 finally 中以确保必须得到调用；如果某个请求的 sequence 未被提交，将会堵塞后续的发布操作或者其它的 producer。
            ringBuffer.publish(sequence);
            log.info("cursor:{},mSeq:{}",ringBuffer.getCursor(),ringBuffer.getMinimumGatingSequence());
        }
    }

}
